package flashcardtest;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// read data from form
		String answer = request.getParameter("button1"); 
		
		// get reference to FlashCardHand and User
		FlashCardHand localHand = (FlashCardHand)request.getSession().getAttribute("flashcardhand");
		//FlashCardSet localset = (FlashCardSet)request.getSession().getAttribute("flashcardset");
		//User localUser = (User)request.getSession().getAttribute("user");

		// initialize result text
		String result = "";
		
		if (localHand == null) {
			request.getSession().setAttribute("message", "localhand was null.");
			response.sendRedirect("/newdictionary.jsp");
			return;
		}
		
		// determine whether answer is correct
		boolean correct = localHand.isCorrect(answer.trim());
		if (correct) {
			// add one to 'correct' score
			//Integer oldscore = (Integer)request.getSession().getAttribute("correct");
			//localUser.correct();
			//request.getSession().setAttribute("correct", new Integer(oldscore.intValue() + 1));
			result = "Correct!";
		}
		else {
			// add one to 'incorrect' score
			//Integer oldscore = (Integer)request.getSession().getAttribute("incorrect");
			//localUser.incorrect();
			//request.getSession().setAttribute("incorrect", new Integer(oldscore.intValue() + 1));
			result = "Incorrect.";
		}
		
		// generate result message
		result = result + " " + localHand.getTestKey() + " matches " + localHand.getTestAnswer(); 
		
		// draw new set of cards
		localHand.draw();
		
		// register result
		request.getSession().setAttribute("result", result );

		response.sendRedirect("/test.jsp");
//		getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

	}

}